﻿@using SmartStore.Web.Framework.UI;
@using Newtonsoft.Json;
@model LocalPluginsModel

@{    
    ViewBag.Title = T("Admin.Configuration.Plugins").Text;

    var allPluginsSelectList = Model.AllPlugins.Select(x => new SelectListItem { Value = x.SystemName, Text = x.FriendlyName });
    var availableStores = JsonConvert.SerializeObject(Model.AvailableStores.Select(x => new { value = x.Id, text = x.Name }).ToArray());

    Html.AddCssFileParts(true, "~/Content/vendors/x-editable/bootstrap-editable.css");
    Html.AppendScriptParts(true, "~/Content/vendors/x-editable/bootstrap-editable.js");
}

@helper PluginList(IEnumerable<PluginModel> plugins)
{
	foreach (var plugin in plugins)
	{
		<div class="module-item@(!plugin.Installed ? " inactive" : "")" data-system-name="@plugin.SystemName" data-friendly-name="@plugin.FriendlyName">
			<div class="module-icon">
				<img class="icon img-responsive" src="@Url.Content(plugin.IconUrl)" />
			</div>
			<div class="module-data row">
				<!-- General -->
				<div class="module-col col-6">
					<div class="module-heading">
						<div>
							<div class="module-title">
								<div class="module-name">@plugin.FriendlyName</div>
								<div class="module-badges">
									@if (plugin.Installed)
									{
										<span class="badge badge-warning">@T("Admin.Configuration.Plugins.Fields.Installed")</span>
									}
									@Html.Partial("LicenseLabel", plugin.LicenseLabel)
								</div>
							</div>
							@if (plugin.Description.HasValue())
							{
								<div class="module-description w-100">
									@plugin.Description
								</div>
							}
						</div>

						@if (plugin.Installed)
						{
							<div class="module-actions dropdown">
								<button class="btn btn-outline-secondary btn-icon dropdown-toggle no-chevron" type="button" data-toggle="dropdown">
									<i class="fa fa-cog"></i>
								</button>
								<div class="dropdown-menu">
									<a class="dropdown-item plugin-update-resources" href="@Url.Action("UpdateStringResources", new { systemName = plugin.SystemName })">
										<i class="fa fa-fw fa-language"></i>
										<span>@T("Admin.Configuration.Plugins.Resources.Update")</span>
									</a>
									@if (plugin.LicenseLabel.LicenseUrl.HasValue())
									{
										<a class="dropdown-item plugin-licence" href="@plugin.LicenseLabel.LicenseUrl">
											<i class="fa fa-fw fa-key"></i>
											<span>@T("Admin.Common.License")</span>
										</a>
									}
									@if (plugin.ConfigurationUrl.HasValue())
									{
										<a class="dropdown-item plugin-configure" href="@plugin.ConfigurationUrl">
											<i class="fa fa-fw fa-cog"></i>
											<span>@T("Admin.Configuration.Plugins.Fields.Configure")</span>
										</a>
									}
								</div>
							</div>
						}
					</div>
					<div class="module-info">
						<span class="attr">
							<span class="attr-name">@T("Admin.Configuration.Plugins.Fields.Version"):</span>
							<span class="attr-value">@plugin.Version</span>
						</span>
						@if (plugin.Author.HasValue())
						{
							<span class="attr">
								<span class="attr-name">@T("Admin.Configuration.Plugins.Fields.Author"):</span>
								<span class="attr-value">@plugin.Author</span>
							</span>
						}
						@if (plugin.Url.HasValue())
						{
							<span class="attr">
								<i class="fa fa-external-link-alt mr-1"></i>
								<a href="@plugin.Url" target="PluginWebsiteWnd">@T("Common.Website")</a>
							</span>
						}
						<span class="attr">
							<span class="attr-name">@T("Admin.Configuration.Plugins.Fields.SystemName"):</span>
							<span class="attr-value">@plugin.SystemName</span>
						</span>
					</div>
					@if (@Model.AvailableStores.Count > 1)
					{
						<div class="fs-sm">
							<span class="pr-2">@T("Admin.Common.Store.LimitedTo"):</span>
							<a href="#" data-pk='@plugin.SystemName' data-value='[@String.Join(",", plugin.SelectedStoreIds)]' class="editable editable-click store-limiter">
								<!-- AJAX -->
							</a>
						</div>
					}
				</div>

				<!-- Buttons -->
				<div class="module-col col-6">
					@if (plugin.Installed)
					{
						<a class="btn btn-secondary btn-to-danger plugin-uninstall" data-toggle="button" href="#" style="min-width: 180px">
							@T("Admin.Configuration.Plugins.Fields.Uninstall")
						</a>
					}
					else
					{
						<a class="btn btn-success plugin-install" data-toggle="button" href="#" style="min-width: 180px">
							<i class="far fa-arrow-alt-circle-down"></i>
							<span>@T("Admin.Configuration.Plugins.Fields.Install")</span>
						</a>
					}
				</div>

			</div>
		</div>
	}
}

@using (Html.BeginForm("ExecuteTasks", null, FormMethod.Post, new { id = "plugins-form" }))
{
    @Html.DropDownList("pluginsToInstall", allPluginsSelectList, new { @class = "d-none noskin", multiple = "multiple" })
    @Html.DropDownList("pluginsToUninstall", allPluginsSelectList, new { @class = "d-none noskin", multiple = "multiple" })

    <div class="section-header">
        <div class="title">
            <i class="fa fa-puzzle-piece"></i>
            @T("Admin.Configuration.Plugins")
        </div>
        <div class="options form-inline">
            @Html.TextBox("filter-query", "", new { @class= "form-control my-0 mr-1", style = "width:350px", placeholder = T("Common.Search").Text })
            <button id="btn-execute-tasks" type="submit" class="btn btn-secondary mr-1" disabled="disabled">
                <i class="fa fa-cogs"></i>
                <span>@T("Admin.Configuration.Plugins.ExecuteTasks")</span>
                <span class="badge badge-dark label-uninstall-count hide">0</span>
                <span class="badge badge-warning label-install-count hide">0</span>
            </button>
			<a id="uploadpackage" href="#uploadpackage-window" data-toggle="modal" class="btn btn-secondary mr-1" role="button">
				<i class="fa fa-upload"></i>
				<span>@T("Admin.Packaging.UploadPlugin")</span>
			</a>
            <div class="dropdown">
                <a class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" href="#">
                    @T("Admin.Common.Edit")
                </a>
                <div class="dropdown-menu dropdown-menu-right">
                    <a href="@Url.Action("ReloadList")" class="dropdown-item" >
                        <i class="fa fa-sync"></i>
						<span>@T("Admin.Configuration.Plugins.ReloadList")</span>
                    </a>                    
                    <a href="@Url.Action("UpdateAllStringResources")" class="plugin-update-allresources dropdown-item">
                        <i class="fa fa-sync"></i>
						<span>@T("Admin.Configuration.Plugins.Resources.UpdateAll")</span>
                    </a>
                </div>
            </div>
        </div>
    </div>

    <div class="alert alert-info alert-dismissible">
		<button type="button" class="close" data-dismiss="alert">&times;</button>
        <h4>@T("Admin.Configuration.Plugins.Description")</h4>
        <ol>
            <li>@Html.Raw(T("Admin.Configuration.Plugins.Description.Step1", "uploadpackage", "#uploadpackage-window"))</li>
            <li>@Html.Raw(T("Admin.Configuration.Plugins.Description.Step2"))</li>
            <li>@Html.Raw(T("Admin.Configuration.Plugins.Description.Step3"))</li>
            <li>@Html.Raw(T("Admin.Configuration.Plugins.Description.Step4"))</li>
        </ol>
    </div>

    <table class="adminContent" id="local-plugins">
        <tr>
            <td>
    
                @foreach (var g in Model.Groups.OrderBy(x => x.Key))
                {
                    <div class="module-list">
						<h3>@g.Key</h3>
						@PluginList(g.Value)
					</div>
                }

                <input type="submit" id="btnRefresh" name="btnRefresh" class="d-none" />
            </td>
        </tr>
    </table>
}

@{Html.SmartStore().Window()
    .Name("plugin-licence-modal")
	.Size(WindowSize.Large)
    .Title(T("Admin.Common.License"))
    .FooterContent(@<text>
		<button class="btn btn-secondary btn-flat" data-dismiss="modal">
			<span>@T("Common.Cancel")</span>
		</button>
		<button class="btn btn-secondary licensing-reset-status-check" data-dismiss="modal">
			<span>@T("Admin.Plugins.LicensingResetStatusCheck")</span>
		</button>
		<button class="btn btn-primary" data-dismiss="modal">
			<span>@T("Common.OK")</span>
		</button>
    </text>)
    .Render();
}

<script type="text/javascript">
	$(document).ready(function () {

		var stores = @Html.Raw(availableStores);

		// Multistore
		$(".store-limiter").editable({
			type: 'checklist',
			title: @T("Admin.Common.Store.AvailableFor").JsText,
			url: '@Url.Action("SetSelectedStores")',
			source: stores,
			unsavedclass: null,
			placement: "right",
			emptytext: @T("Common.No").JsText,
			autotext: 'always',
			display: function (value, sourceData) {
				//display checklist as comma-separated values
				var html = [],
					checked = $.fn.editableutils.itemsByValue(value, sourceData);

				if (checked.length) {
					$.each(checked, function (i, v) { html.push($.fn.editableutils.escape(_.str.truncate(v.text, 40))); });
					$(this).html(html.join(', '));
				} else {
					$(this).empty();
				}
			}
		});

		function getPluginFriendlyName(dropdown, systemName) {
			return dropdown.find('option[value="{0}"]'.format(systemName)).text();
		}

		var dropdownInstall = $('#pluginsToInstall'),
            dropdownUninstall = $('#pluginsToUninstall'),
			btnExecuteTasks = $('#btn-execute-tasks')
			inputFilterQuery = $('#filter-query');
			
		// Execute filtering
		setTimeout(function() {
			inputFilterQuery.focus();
		}, 800);

		var mainContainer = $('#local-plugins');
		inputFilterQuery.on('input propertychange paste', function (e) {
			var el = $(this);

			// store query
			sessionStorage.setItem("plugin-filter-query", el.val());

			// Retrieve the input field text and reset the count to zero
			var filter = el.val(),
                rg = new RegExp(filter, "i");

			// Loop through the plugin items
			$('.module-list').each(function () {
				var group = $(this),
                    count = 0;

				group.find('.module-item').each(function () {
					// If the list item does not contain the text phrase hide it
					if (filter.length > 1 && $(this).data('system-name').search(rg) < 0 && $(this).data('friendly-name').search(rg) < 0) {
						$(this).hide();
					}
						// Show the list item if the phrase matches and increase the count by 1
					else {
						$(this).show();
						count++;
					}
				});

				if (count > 0) {
					group.show();
				}
				else {
					group.hide();
				}
			});

			if (!mainContainer.visible(true)) {
				$.scrollTo(mainContainer, 400, { offset: -50 });
			}
		});

		// restore search query
		var data = sessionStorage.getItem('plugin-filter-query');
		if (data) {
			inputFilterQuery.val(data);
			inputFilterQuery.trigger("paste");
		}

		// Create tooltip for  ExecuteTasks button which informs
		// about plugins to be installed and uninstalled
		btnExecuteTasks.tooltip({
			html: true,
			placement: 'bottom',
			title: function () {
				var text = '';

				if (dropdownUninstall.val()) {
					text = '<div class="al"><b>' + @T("Admin.Configuration.Plugins.Fields.Uninstall").JsText + ':</b></div>';
					_.each(dropdownUninstall.val(), function (val, i) {
						text += '<div class="al">{0}</div>'.format(getPluginFriendlyName(dropdownUninstall, val));
					});
				}

				if (dropdownInstall.val()) {
					if (text) text += '<div style="height: 6px"></div>';
					text += '<div class="al"><b>' + @T("Admin.Configuration.Plugins.Fields.Install").JsText + ':</b></div>';
					_.each(dropdownInstall.val(), function (val, i) {
						text += '<div class="al">{0}</div>'.format(getPluginFriendlyName(dropdownInstall, val));
					});
				}

				return text;
			}
		});

		// Add/Remove plugins to/from the list of (un)installable plugins
		$('#plugins-form').on('click', 'a.plugin-install, a.plugin-uninstall', function (e) {
			e.preventDefault();

			var el = $(this),
                systemName = el.closest('.module-item').data('system-name'),
                dropdown = null;

			if (el.hasClass("plugin-install")) {
				dropdown = dropdownInstall;
			}
			else if (el.hasClass("plugin-uninstall")) {
				dropdown = dropdownUninstall;
			}

			// set the corresponding dropdown's option to selected
			var wasRemoved = false;
			var option = dropdown.find('option[value="{0}"]'.format(systemName));
			if (option.attr('selected')) {
				option.removeAttr('selected');
				wasRemoved = true;
			}
			else {
				option.attr('selected', 1);
			}

			var transferSrc = wasRemoved ? btnExecuteTasks : el;
			var transferTarget = wasRemoved ? el : btnExecuteTasks;

			transferSrc.stop(true, true).effect("transfer", { to: transferTarget, easing: "easeOutQuad", className: "transfer" }, 400, function () {
				// Toggle the ExecuteTasks button and it's labels
				var labelInstall = btnExecuteTasks.find('.label-install-count'),
                    labelUninstall = btnExecuteTasks.find('.label-uninstall-count'),
                    installCount = dropdownInstall.val() ? dropdownInstall.val().length : 0,
                    uninstallCount = dropdownUninstall.val() ? dropdownUninstall.val().length : 0;

				labelInstall.toggleClass('hide', installCount == 0).text(installCount);
				labelUninstall.toggleClass('hide', uninstallCount == 0).text(uninstallCount);

				if (!installCount && !uninstallCount) {
					btnExecuteTasks.attr('disabled', 'disabled');
				}
				else {
					btnExecuteTasks.removeAttr('disabled');
				}
			});

		});

		// Execute the install actions
		btnExecuteTasks.on('click', function (e) {
			var confirmText = @T("Admin.Configuration.Plugins.ExecuteTasks.Confirm").JsText;
			var progressText = @T("Admin.Configuration.Plugins.ExecuteTasks.Progress").JsText;

			if (!confirm(_.str.unescapeHTML(confirmText))) {
				e.preventDefault();
				return false;
			}

			$.throbber.show({
				message: progressText
			});
		});

		// Update (all) plugin resources
		$('#plugins-form').on('click', 'a.plugin-update-resources, a.plugin-update-allresources', function (e) {
			e.preventDefault();
			var el = $(this);

			var confirmText = @T("Admin.Configuration.Plugins.Resources.UpdateConfirm").JsText,
                confirmAllText = @T("Admin.Configuration.Plugins.Resources.UpdateAllConfirm").JsText,
                progressText = @T("Admin.Configuration.Plugins.Resources.UpdateProgress").JsText;

			if (!confirm(_.str.unescapeHTML(el.hasClass('plugin-update-allresources') ? confirmAllText : confirmText))) {
				return false;
			}

			$.throbber.show({
				message: progressText,
				callback: function () {
					setLocation(el.attr("href"));
				}
			});
		});

		// edit plugin
		$('#plugins-form').on('click', '.plugin-edit', function (e) {
			openPopup(
                '{0}?systemName={1}&btnId=btnRefresh&formId=plugins-form'.format(
                    '@Url.Content("~/Admin/Plugin/EditPopup")',
                    $(this).data("systemname")
                )
            );
            return false;
        });

    	// licence plugin
		$(document).on('click', '.plugin-licence', function (e) {
			e.preventDefault();

    		var dialog = $('#plugin-licence-modal'),
				url = $(this).attr('href');

    		dialog.find('.modal-body').empty();

    		$(this).doAjax({
    			type: 'GET',
    			smallIcon: dialog.find('.modal-body'),
    			callbackSuccess: function (resp) {
    				dialog = $('#plugin-licence-modal');
    				dialog.find('.modal-body').html(resp);

    				setTimeout(function() {
    					dialog.find('[name="Licenses[0].LicenseKey"]').focus();
    				}, 1000);

    				dialog.find('.btn-primary').click(function(e2) {
    					e2.preventDefault();
    					if (confirm(@T("Admin.Configuration.Plugins.ConfirmLicensing").JsText)) {
    						dialog.find('form:first').submit();
    					}
    					return false;
    				});
    			}
    		});

			dialog.modal('show');

    		return false;
    	});

		// reset license status
		$('#plugin-licence-modal').on('click', '.licensing-reset-status-check', function() {
			var licenseForm = $('#plugin-licence-modal').find('.modal-body form:first');
			$({}).doAjax({
				type: 'POST',
				url: licenseForm.attr('data-resetcheckurl'),
				callbackSuccess: function (resp) {
					if (resp.length > 0) {
						var systemName = licenseForm.attr('data-systemname');
						$('#local-plugins').find('div[data-system-name="' + systemName + '"]').find('.license-label').html(resp);
					}
				}
			});
		});

        $('#btnRefresh').click(function () {
            // reload page
            setLocation(location.href);
            return false;
        });
    });
</script>

@{ Html.RenderAction("UploadPackage", "Packaging", new { isTheme = false }); }